#!/bin/bash

if [[ $# > 1 ]]; then
	wb=$2
elif [[ $# == 1 ]]; then
	wb=/mnt/d/OneDrive/workbench
else
	exit 1
fi

if [[ $# > 2 ]]; then day=$3; else day=30; fi

backDir=${1}
oldFiles=`find $backDir -type f -mtime +30`
if [[ ${oldFiels} ]]; then rm $oldFiles ; fi

if [[ `find ${backDir} -name "*.tgz"` ]]; then
	lastFile=`ls -t ${backDir}/*.tgz | head -n 1`
else 
	lastFile=""
fi
if [[ $day < 32 ]]; then
	newFile=$(date +\%d_\%H_\%M).tgz
elif [[ $day < 367 ]]; then
	newFile=$(date +\%m_\%d).tgz
else
	newFile=$(date +\%Y_\%m).tgz
fi

expiredFiles=`find ${backDir} -mtime +${day}`
if [[ $expiredFiles ]]; then rm $expiredFiles; fi

cd $wb
files=`find -type f -mtime -${day} -a \( -name "*\.[c,h,f,m,C]" -o -name "*.cpp" -o  -name "*\.F90" -o -name "*\.sh" -o -name "in\.*" -o -name "*\.cc" -o -name "*\.py" -o -name "gen-*" \
		-o -name "*\.inf" -o -name "*\.yaml" -o -name "*\.ctrl" -o -name "fm*dat" -o -name "*\.py" -o -name "*\.gen" -o -name "*\.md" -o -name "*\.txt" -o -name "README*" \
		-o -name "*\.yal" -o -name "*\.json" -o -name "*\.st" -o -name "*\.tex" -o -name "*\.nb" -o -name "*\.mw" -o -name "*\.jl" -o -name "[M,m]akefile" -o -name "*\.opj*" -o -name "*\.gp" \
		-o -name "*\.ipynb" \) \
		|  egrep -v "docs/latex|docs/html|build|/target/"`
if [[ $files == "" ]]; then exit 1; fi
tar -zcvf ${newFile} $files
md51=`md5sum -b $newFile | cut -d " " -f 1`
if [[ $lastFile ]]; then
	md52=`md5sum -b $lastFile | cut -d " " -f 1`
	if [ "${md52}"  == "${md51}" ]; then 
		rm $newFile; 
	else 
		mv $newFile ${backDir}/$newFile
	fi
else
	mv $newFile ${backDir}/$newFile
fi

